using System;
using System.Collections.Generic;
using System.Windows;
using GradeApp.Views;
using GradeApp.Web;
using GradeApp.Web.Services;

namespace GradeApp.ViewModels
{
    public class HomeViewModel : ViewModelBase
    {
        private GradeAppDomainContext _gradeAppDomainContext;

        private Visibility _mainLinksPanelVisibility;
        public Visibility MainLinksPanelVisibility
        {
            get { return _mainLinksPanelVisibility; }
            set
            {
                if (_mainLinksPanelVisibility != value)
                {
                    _mainLinksPanelVisibility = value;
                    OnPropertyChanged("MainLinksPanelVisibility");
                }
            }
        }


        private Visibility _chooseCoursePanelVisibility;
        public Visibility ChooseCoursePanelVisibility
        {
            get { return _chooseCoursePanelVisibility; }
            set
            {
                if (_chooseCoursePanelVisibility != value)
                {
                    _chooseCoursePanelVisibility = value;
                    OnPropertyChanged("ChooseCoursePanelVisibility");
                }
            }
        }


        private IEnumerable<Courses> _allCourses;
        public IEnumerable<Web.Courses> AllCourses
        {
            get { return _allCourses; }
            set
            {
                _allCourses = value;
                OnPropertyChanged("AllCourses");
            }
        }


        private void UpdateForUserRole()
        {
            var isLoggedIn = WebContext.Current.User.IsAuthenticated;

            if (isLoggedIn)
            {
                GradeAppContext.GetCurrentUserData();
            }
            else
            {
                GradeAppContext.CurrentTutorId = Guid.Empty;
                GradeAppContext.CurrentTutor = null;
            }

            ChooseCoursePanelVisibility = isLoggedIn ? Visibility.Visible : Visibility.Collapsed;
            MainLinksPanelVisibility = isLoggedIn ? Visibility.Visible : Visibility.Collapsed;
        }


        public HomeViewModel()
        {
            GradeAppContext.AllCoursesUpdated += (s, e) => UpdateAllCourses();
            WebContext.Current.Authentication.LoggedIn += (s, e) => UpdateForUserRole();
            WebContext.Current.Authentication.LoggedOut += (s, e) => UpdateForUserRole();
            UpdateForUserRole();
        }

        private void UpdateAllCourses()
        {
            AllCourses = GradeAppContext.AllCourses;
        }
    }
}